import React from "react";

import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import { BrowserRouter as Router,Link } from 'react-router-dom';//
import Button from "antd/lib/button";
import Col from "antd/lib/col";
import Divider from "antd/lib/divider";
import Form from "antd/lib/form";
import Row from "antd/lib/row";
import Table from "antd/lib/table";
import ConfigProvider from "antd/lib/config-provider";
import Layout from "antd/lib/layout";
import Modal from "antd/lib/modal";
import AutoComplete from "antd/lib/auto-complete";
import zhCN from 'antd/es/locale/zh_CN';
import EmployeeChange from "@/services/employeechange";
import {createBrowserHistory} from 'history'
import { currentUser } from "@/services/auth";
import routes from "@/services/routes";
import notification from "@/services/notification";
import {get} from "lodash";

const customHistory = createBrowserHistory();
const { confirm } = Modal;
const getRowClassName = (record, index) => {
  let className = '';
  if (index % 2 === 0) className = "oddRow";
  return className
}
class EmployeeChangeList extends React.Component {
  state = {
    page: 1,
    pagesize: localStorage.getItem("employeechangelistpagesize") ? (localStorage.getItem("employeechangelistpagesize") !== undefined ? Number(localStorage.getItem("employeechangelistpagesize")) : 20) : 20,
    total:1,
    order: 1,
    loading: false,
    code: localStorage.getItem("employeechangelistcode") ? (localStorage.getItem("employeechangelistcode")!== undefined ? localStorage.getItem("employeechangelistcode"):'') : '',
    name: localStorage.getItem("employeechangelistname")? (localStorage.getItem("employeechangelistname")!== undefined ? localStorage.getItem("employeechangelistname"):'') : '',
    major: localStorage.getItem("employeechangelistmajor") ? (localStorage.getItem("employeechangelistmajor")!== undefined ? localStorage.getItem("employeechangelistmajor"):'') : '',
    area: localStorage.getItem("employeechangelistarea")? (localStorage.getItem("employeechangelistarea")!== undefined ? localStorage.getItem("employeelistarea"):'') : '',
    bytstatus: localStorage.getItem("employeechangelistbytstatus")? (localStorage.getItem("employeechangelistbytstatus")!== undefined ? localStorage.getItem("employeechangelistbytstatus"):'') : '',
    data: [],
  };
  componentWillMount() {
    let param={
      page: this.state.page,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      major: this.state.major,
      area: this.state.area,
      userid: currentUser.id,
      id:0,
      bytstatus: this.state.bytstatus,
      datadown: false,
    }
    this.seldata(param);
  }
  isEmptyobj = (str) => {
    if(str==='' || str === null || str === 'null' || str === undefined || str === 'undefined'){
        return true;
    }else{
        return false;
    }
}
  seldata = (params = {}) => {

    if(params.datadown){
      let AjaxUrl = 'api/employeechange/list';
      fetch(AjaxUrl ,{
       method: 'POST',
       body: window.JSON.stringify(params),
       credentials: 'include',
       headers: new Headers({
         'Content-Type': 'application/json'
       })}).then((response) => {
       response.blob().then(blob => {
         const aLink = document.createElement('a');
         document.body.appendChild(aLink);
         aLink.style.display='none';
         const objectUrl = window.URL.createObjectURL(blob);
         aLink.href = objectUrl;
         aLink.download = '人员信息.xlsx';
         aLink.click();
         document.body.removeChild(aLink);
       });
     }).catch((error) => {
       window.console.log(error);
     });
    }
    else{
      this.setState({ loading: true });
      EmployeeChange.getlist(params).then(data => {
          this.setState({
              loading: false,
              data:data.data,
              page: params.page,
              pagesize: params.pagesize,
              total: data.total,
              field: params.field,
              order: params.order,
          });
      });
    }
  };
  bill_dateonchange = (value) => {
      localStorage.setItem("bill_date", value);
        this.setState({
          bill_date: value,
      });
   };

  handlesel = (index) => {
    let datadown =false;
    if(index===2){
      datadown =true;
    }
    let param={
      page: 1,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      major: this.state.major,
      area: this.state.area,
      userid: currentUser.id,
      id:0,
      bytstatus: this.state.bytstatus,
      datadown: datadown,
    }
    this.seldata(param);
  };
  handleDelete = record => {
    if(record.blnisinactive)
    {
       notification.error("只有在草稿状态可以删除，删除失败！");
       return;
    }
    if(!currentUser.hasPermission("admin"))
    {
       notification.error("只有管理员可以删除，删除失败！");
       return;
    }
    confirm({
      title: '确定删除?',
      content: record.code,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        EmployeeChange.delete(record).then(()=>{
          notification.success("删除成功.");
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            code: this.state.code,
            name: this.state.name,
            major: this.state.major,
            area: this.state.area,
            userid: currentUser.id,
            datadown: false,
          }
          this.seldata(param);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
   handleTableChange = (pagination, filters, sorter) => {
    localStorage.setItem("employeechangelistpagesize", pagination.pageSize);
    let field=sorter.field;
    let order=0;
    if(sorter.order==="descend"){
      order=1;
    }
    let param={
      field: field,
      order: order,
      page: pagination.current,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      major: this.state.major,
      area: this.state.area,
      userid: currentUser.id,
      datadown: false,
    }
    this.seldata(param);
  };
onDragEnter = info => {
    window.console.log(info);
  };
  render() {
    const paginationProps = {
            showSizeChanger: true,
            total: this.state.total, // 数据总数
            pageSize: parseInt(this.state.pagesize), // 每页条数
            current: parseInt(this.state.page), // 当前页码
            pageSizeOptions: ["10", "20", "30","100"],
            showTotal: ((total) => {
              return `共 ${total} 条`;
            }),
          };
    let listcolumns = [];
    listcolumns.push({
    title: '人员编码',
    key: 'code',
    dataIndex: 'code',
    render: (text, record) => (
        <Router  history={customHistory}>
        <Link to={`/employeechange/new/${record.id}`} target="_blank">{text}</Link>
        </Router>
    ),
    sorter: (a, b) => a.code > b.code ? 1 : -1
    });
      listcolumns.push({
        title: '人员名称',
        dataIndex: 'name',
        key: 'name',
        sorter: (a, b) => a.name > b.name ? 1 : -1
      });
      listcolumns.push({
        title: '起草日期',
        dataIndex: 'bill_dateformat',
        key: 'bill_dateformat',
        sorter: (a, b) => a.bill_dateformat > b.bill_dateformat ? 1 : -1
      });
      listcolumns.push({
        title: '毕业专业',
        dataIndex: 'major',
        key: 'major',
        sorter: (a, b) => a.major > b.major ? 1 : -1
      });
      listcolumns.push({
        title: '区域',
        dataIndex: 'area',
        key: 'area',
        sorter: (a, b) => a.area > b.area ? 1 : -1
      });
      listcolumns.push({
        title: '状态',
        dataIndex: 'bytstatus',
      //  width: 100,
        key: 'bytstatus',
        render: (text, record) => (
          <span>
            <label>
              {text}
            </label>
          </span>
                  ),
        sorter: (a, b) => a.bytstatus > b.bytstatus ? 1 : -1
      });
      window.console.log(listcolumns);
    return (
  <ConfigProvider locale={zhCN}>
      <div  style={{width:"400px",height:"60px"}}>
        <div style={{width:"20px",height:"50px", float: "left"}}>
        </div>
          <div style={{width:"50px",height:"50px", float: "left"}}>
          <img src="/static/images/employeechangelist.png"  alt="HR"  loading="lazy"/>
        </div>
          <div style={{width:"320px",height:"30px",float:"left"}}>
          <h3 style={{margin:"7px",padding:"0"}}>人员信息列表</h3>
        </div>
        </div>
       <Layout>
         <Layout style={{ padding: '0 24px 24px' }}> 
        <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
          <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="人员编码">
              <AutoComplete
                style={{ width: 400 }}
                value={this.state.code} 
                onChange={value => {
                  localStorage.setItem("employeechangelistcode", value);
                  this.setState({code:value});}}
                placeholder="人员编码"
                filterOption={(inputValue, option) => 
                  option.value.indexOf(inputValue) !== -1}>
              </AutoComplete>
            </Form.Item>
				  </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="人员名称">
              <AutoComplete
                style={{ width: 400 }}
                value={this.state.name} 
                onChange={value => {
                  localStorage.setItem("employeechangelistname", value);
                  this.setState({name:value});}}
                placeholder="人员名称"
                filterOption={(inputValue, option) => 
                  option.value.indexOf(inputValue) !== -1}>
              </AutoComplete>
            </Form.Item>
				  </Col>
        </Row>
        <Row>
			<Col span={10}>
                <Form.Item style={{ marginBottom: 5 }} label="毕业专业">
                <AutoComplete
                    style={{ width: 400 }}
                    value={this.state.major} 
                    onChange={value => {
                    localStorage.setItem("employeechangelistmajor", value);
                    this.setState({major:value});}}
                    placeholder="毕业专业"
                    filterOption={(inputValue, option) => 
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
                </Form.Item>
            </Col>
			<Col span={10}>
                <Form.Item style={{ marginBottom: 5 }} label="区域">
                    <AutoComplete
                        style={{ width: 400 }}
                        value={this.state.area} 
                        onChange={value => {
                        localStorage.setItem("employeechangelistarea", value);
                        this.setState({area:value});}}
                        placeholder="区域"
                        filterOption={(inputValue, option) => 
                        option.value.indexOf(inputValue) !== -1}>
                        {/* {(this.state.customerdata || []).map(item => (
                        <AutoComplete.Option key={item.strcustomername} value={item.strcustomername}>{item.strcustomername}</AutoComplete.Option>
                        ))} */}
                    </AutoComplete>
                </Form.Item>
            </Col>
        </Row>
        <Row>
			<Col span={10}>
                <Form.Item style={{ marginBottom: 5 }} label="状态">
                <AutoComplete
                    style={{ width: 400 }}
                    value={this.state.bytstatus} 
                    onChange={value => {
                    localStorage.setItem("employeechangelistbytstatus", value);
                    this.setState({bytstatus:value});}}
                    placeholder="状态"
                    filterOption={(inputValue, option) => 
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
                </Form.Item>
            </Col>
        </Row>
        <Row>
			<Col span={10}>
                <Button type="primary" onClick={() => this.handlesel(1)} >
                    <i className="fa fa-search m-r-5" />
                    查询
                </Button>
                <Divider type="vertical" />
                <Button type="primary" onClick={() => this.handlesel(2)} >
                    <i class="fa fa-file-excel-o  m-r-5" />
                    导出EXCEL
                </Button>
                <Divider type="vertical" />
			</Col>
        </Row>
      </Form>
            <div>
                <Table rowKey='id'
                        rowClassName={(record, index) => getRowClassName(record, index)}
                        columns={listcolumns}
                        scroll={{x:'max-content'}}
                        dataSource={this.state.data}
                        pagination={paginationProps}
                        loading={this.state.loading}
                        onChange={this.handleTableChange}
                />
            </div>
         {/* </Layout>*/}
        </Layout> 
       </Layout> 
  </ConfigProvider>
    );
  }
}

routes.register(
  "EmployeeChange.List",
  routeWithUserSession({
    path: "/employeechange",
    title: "提交的人员变更信息",
    render: pageProps => <EmployeeChangeList {...pageProps} warns="0"/>,
  })
);
routes.register(
  "Employeechange.List1",
  routeWithUserSession({
    path: "/employeechange/approve",
    title: "人员信息变更列表",
    render: pageProps => <EmployeeChangeList {...pageProps} warns="0"/>,
  })
);
